import { join } from "path";
import { cwd } from "process";
import * as fs from "fs"
import { promisify } from "util";
const { existsSync } = fs
const assets = join(cwd(), "public")
export const taskDir = (id: number) => join(assets, id + "")
export const taskFile = (id: number, fileName: string) => join(taskDir(id), fileName)
export const readdir = promisify(fs.readdir);
export const stat = promisify(fs.stat);
export const unlink = promisify(fs.unlink);
export const rmdir = promisify(fs.rmdir);
export const mkdir = promisify(fs.mkdir);
export const writefile = promisify(fs.writeFile)
export const unlinkDir = async (path: string) => {
    if (!existsSync(path)) return;
    const s = await stat(path);
    if (s.isDirectory()) {
        const names = await readdir(path)
        for (const name of names) {
            await unlinkDir(join(path, name));
        }
        await rmdir(path)
        return;
    }
    await unlink(path)
}

export const makeDir = async (path: string) => {
    if (existsSync(path)) return;
    const before = join(path, "..");
    if (!existsSync(before)) {
        await makeDir(before);
    }
    await mkdir(path);
}
